package com.rules.admin.controller;

import com.fasterxml.jackson.databind.node.ObjectNode;

import com.gillion.grule.client.utils.Collections3;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.rules.admin.domain.SysResource;
import com.rules.admin.domain.UserInfoAttributesConverter;
import com.rules.admin.service.ResourceService;
import com.rules.admin.utils.JsonMapperHolder;
import com.rules.admin.utils.ResourceUtils;
import com.rules.admin.utils.UserUtils;
import com.rules.admin.vo.RuleUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RequestMapping({"/system/security"})
public class SecurityController {
   @Autowired
   private ResourceService resourceService;
   @Autowired
   private UserInfoAttributesConverter userInfoAttributesConverter;
   @Value("#{securityProps['login.page']}")
   private String loginPage;
   @Value("#{securityProps['index.page']}")
   private String indexPage;
   @Value("#{securityProps['isRedirectLastRequestPage']}")
   private boolean isRedirectLastRequestPage;

   @ResponseBody
   @RequestMapping({"/getSessionAttrsAndNoPermits"})
   public ObjectNode getSessionAttrsAndNoPermits(@RequestParam String pageUrl) {
      ObjectNode sessionAttrsAndNoPermits = JsonMapperHolder.createObjectNode();
      boolean hasPermissions = this.isCurrentUserHasPermission(pageUrl);
      if (!UserUtils.getCurrentLoginUser().equals(RuleUser.ANONYMOUS_USER) && this.isLoginPage(pageUrl)) {
         if (!this.isCurrentUserHasPermission(this.indexPage)) {
            sessionAttrsAndNoPermits.set("sessionAttrs", this.getSessionAttrs());
         }
      } else if (!this.isLoginPage(pageUrl) && !hasPermissions) {
         if (this.isRedirectLastRequestPage) {
         }

         sessionAttrsAndNoPermits.set("redirectUrl", JsonMapperHolder.convert(this.loginPage));
      } else {
         final HttpServletRequest mockRequest = ResourceUtils.mockRequestByRequestUrl(pageUrl);
         Map<AntPathRequestMatcher, SysResource> urlMatcherWithResource = this.resourceService.loadAllUrlMatcherWithResource();
         Optional<AntPathRequestMatcher> resourceMatcher = Iterables.tryFind(urlMatcherWithResource.keySet(), new Predicate<AntPathRequestMatcher>() {
            public boolean apply(AntPathRequestMatcher matcher) {
               return matcher.matches(mockRequest);
            }
         });
         if (resourceMatcher.isPresent()) {
            Iterable<String> pageChildrenResourceUrlPatterns = Iterables.transform(((SysResource)urlMatcherWithResource.get(resourceMatcher.get())).getChildren(), new Function<SysResource, String>() {
               public String apply(SysResource input) {
                  return input.getUrl();
               }
            });
            List<String> noPermissionUrlPatterns = Collections3.subtract(Sets.newHashSet(pageChildrenResourceUrlPatterns), UserUtils.getCurrentLoginUser().getHasPermissionUrlPatterns());
            sessionAttrsAndNoPermits.set("noPermits", JsonMapperHolder.convert(noPermissionUrlPatterns));
         }

         sessionAttrsAndNoPermits.set("sessionAttrs", this.getSessionAttrs());
      }

      return sessionAttrsAndNoPermits;
   }

   private boolean isLoginPage(@RequestParam String pageUrl) {
      return StringUtils.endsWith(this.loginPage, pageUrl);
   }

   private boolean isCurrentUserHasPermission(String pageUrl) {
      HttpServletRequest servletRequest = ResourceUtils.mockRequestByRequestUrl(pageUrl);
      Map<AntPathRequestMatcher, SysResource> antPathRequestMatcherMap = this.resourceService.loadAllUrlMatcherWithResource();
      Set<AntPathRequestMatcher> keys = antPathRequestMatcherMap.keySet();
      Iterator var5 = keys.iterator();

      AntPathRequestMatcher matcher;
      do {
         if (!var5.hasNext()) {
            return true;
         }

         matcher = (AntPathRequestMatcher)var5.next();
      } while(!matcher.matches(servletRequest));

      return UserUtils.getCurrentEffectiveLoginUser().matches(servletRequest);
   }

   private ObjectNode getSessionAttrs() {
      return this.userInfoAttributesConverter.getUserInfoAttributes();
   }
}
